<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="医生名" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!--  搜索条件里的所属科室 -->
      <el-form-item label="所属科室" prop="doctorDepartmentId">
        <el-cascader
          v-model="queryParams.doctorDepartmentId"
          :options="departmentOptions"
          placeholder="请选择所属科室"
          clearable
          @visible-change="handleDeptVisibleChange"
        >
          <template slot-scope="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>

      <el-form-item label="医生手机号码" prop="doctorPhoneNumber">
        <el-input
          v-model="queryParams.doctorPhoneNumber"
          placeholder="请输入医生手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生职称" prop="doctorLevelId">
        <el-select
          v-model="queryParams.doctorLevelId"
          placeholder="请选择医生职称"
          clearable
        >
          <el-option
            v-for="item in dictOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="医生状态" prop="doctorStatus">
        <el-select
          v-model="queryParams.doctorStatus"
          placeholder="请选择医生状态"
          clearable
        >
          <el-option
            v-for="item in doctorStatusOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:doctor:add']"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="doctorList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="医生id" align="center" prop="doctorId" />
      <el-table-column label="所属管理员" align="center">
        <template slot-scope="scope">
          {{
            (
              adminOptions.find(
                (admin) => admin.value === scope.row.doctorAdminId
              ) || {}
            ).label || "未知管理员"
          }}
        </template>
      </el-table-column>
      <el-table-column label="医生名" align="center" prop="doctorName" />
      <el-table-column label="医生身份证" align="center" prop="doctorIdCard" />
      <el-table-column
        label="所属科室"
        align="center"
        prop="departmentDO.departmentName"
      />
      <el-table-column
        label="医生手机号码"
        align="center"
        prop="doctorPhoneNumber"
      />
      <el-table-column label="医生职称" align="center">
        <template slot-scope="scope">
          {{ getDoctorLevelLabel(scope.row.doctorLevelId) }}
        </template>
      </el-table-column>

      <el-table-column label="医生评分" align="center" prop="doctorRating" />
      <el-table-column
        label="医生简介"
        align="center"
        prop="doctorDescription"
      />
      <el-table-column label="医生特长" align="center" prop="doctorSpecialty" />
      <el-table-column label="医生状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.doctorStatus"
            active-color="#13ce66"
            active-text="启用"
            inactive-color="#ff4949"
            inactive-text="禁用"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:doctor:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:doctor:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 添加或修改医生对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="所属管理员" prop="doctorAdminId">
          <el-select
            v-model="form.doctorAdminId"
            placeholder="请选择管理员"
            clearable
          >
            <el-option
              v-for="admin in adminOptions"
              :key="admin.value"
              :label="admin.label"
              :value="admin.value"
              :disabled="isAdminDisabled(admin)"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="医生名" prop="doctorName">
          <el-input v-model="form.doctorName" placeholder="请输入医生名" />
        </el-form-item>
        <el-form-item label="密码" prop="adminPassword" v-if="!form.doctorId">
          <el-input
            type="password"
            v-model="form.adminPassword"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="医生身份证" prop="doctorIdCard">
          <el-input
            v-model="form.doctorIdCard"
            placeholder="请输入医生身份证"
          />
        </el-form-item>

        <!-- ✅ 新增/编辑里的所属科室 改成 cascader -->
        <el-form-item label="所属科室" prop="doctorDepartmentId">
          <el-cascader
            v-model="form.doctorDepartmentId"
            :options="departmentOptions"
            placeholder="请选择所属科室"
            clearable
            @visible-change="handleDeptVisibleChange"
          >
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>

        <el-form-item label="医生手机号码" prop="doctorPhoneNumber">
          <el-input
            v-model="form.doctorPhoneNumber"
            placeholder="请输入医生手机号码"
          />
        </el-form-item>
        <el-form-item label="医生职称" prop="doctorLevelId">
          <el-select
            v-model="form.doctorLevelId"
            placeholder="请选择医生职称"
            clearable
          >
            <el-option
              v-for="item in dictOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="每周最大工作时长"
          prop="doctorMaxWorkHour"
          v-if="form.doctorId"
        >
          <el-input
            v-model="form.doctorMaxWorkHour"
            placeholder="请输入每周最大工作时长"
          />
        </el-form-item>
        <el-form-item label="医生简介" prop="doctorDescription">
          <el-input
            v-model="form.doctorDescription"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="医生特长" prop="doctorSpecialty">
          <el-input
            v-model="form.doctorSpecialty"
            placeholder="请输入医生特长"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartmentOptions,
  getDoctorList,
  updateDoctorStatus,
  deleteDoctor,
  addDoctor,
  updateDoctor,
} from "@/api/medicalManament/doctor";
import { getDicts } from "@/api/system/dict/data";
import { listUser } from "@/api/system/user";
export default {
  name: "Doctor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医生表格数据
      doctorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      dictOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        doctorName: null,
        doctorDepartmentId: null,
        doctorPhoneNumber: null,
        doctorLevelId: null,
        doctorStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        doctorName: [
          { required: true, message: "医生名不能为空", trigger: "blur" },
        ],
        doctorDepartmentId: [
          { required: true, message: "所属科室不能为空", trigger: "change" },
        ],
        doctorMaxWorkHour: [
          {
            required: true,
            message: "每周最大工作时长不能为空",
            trigger: "blur",
          },
          { validator: this.validateMaxWorkHour, trigger: "blur" },
        ],
        adminPassword: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "密码长度在6-20个字符之间",
            trigger: "blur",
          },
        ],
        doctorLevelId: [
          { required: true, message: "医生职称不能为空", trigger: "change" },
        ],
      },
      //  部门树数据
      departmentOptions: [],
      // 管理员信息
      adminOptions: [],
      // 存储已绑定医生的管理员id
      boundAdminIds: new Set(),

      doctorStatusOptions: [],
    };
  },
  created() {
    this.getList();
    this.getDictData();
    this.getAllAdmins();
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryParams.pageNum = val;
      this.getList();
    },
    // 判断输入的最大工作时长是否合理
    validateMaxWorkHour(rule, value, callback) {
      if (value === null || value === "") {
        callback(new Error("每周最大工作时长不能为空"));
      } else if (value <= 0) {
        callback(new Error("每周最大工作时长不能小于0"));
      } else if (value > 40) {
        callback(new Error("每周最大工作时长不能超过40"));
      } else {
        callback(); // 验证通过
      }
    },
    // 判断管理员是否禁用
    isAdminDisabled(admin) {
      // 1. 超级管理员禁用
      if (admin.value == 1) {
        return true;
      }
      // 2. 已经绑定医生的禁用（但如果是当前医生的绑定则允许选择）
      if (admin.hasDoctor) {
        return true; // 禁用已绑定的管理员
      }
      return false;
    },
    // 获取所有的管理员信息
    getAllAdmins() {
      listUser({}).then((res) => {
        console.log(res);
        this.adminOptions = res.rows.map((admin) => ({
          value: admin.userId,
          label: admin.userName,
          hasDoctor: this.boundAdminIds.has(admin.userId), // 判断是否绑定医生
        }));
        console.log("所有管理员", this.adminOptions);
      });
    },
    // 查找字典
    getDictData() {
      getDicts("doctor_level_name") // 替换为你的字典类型
        .then((response) => {
          console.log(response);
          this.dictOptions = response.data;
        });
      getDicts("doctor_status") // 替换为你的字典类型
        .then((response) => {
          console.log(response);
          this.doctorStatusOptions = response.data;
        });
    },
    // 查找对应的字典label
    getDoctorLevelLabel(levelId) {
      const level = this.dictOptions.find(
        (item) => String(item.dictValue) === String(levelId)
      );
      console.log(level);
      return level ? level.dictLabel : levelId; // 如果找不到则返回原始值
    },
    /** 查询医生列表 */
    getList() {
      this.loading = true;
      getDoctorList(this.queryParams).then((response) => {
        console.log("医生", response);
        this.doctorList = response.rows;
        // 提取已绑定医生的管理员 ID
        this.boundAdminIds = new Set(
          this.doctorList.map((doctor) => doctor.doctorAdminId)
        );
        this.total = response.total;
        this.loading = false;
        this.getAllAdmins();
      });
    },
    /** 获取部门树 */
    getDepartment() {
      getDepartmentOptions().then((res) => {
        console.log(res);
        this.departmentOptions = this.transformData(res.data.data);
        console.log(this.departmentOptions);
      });
    },
    transformData(data) {
      return data
        .map((item) => {
          // 仅当有子项时，才添加 children
          const children =
            item.children && item.children.length > 0
              ? item.children.map((child) => ({
                  value: child.departmentId,
                  label: child.departmentName,
                }))
              : null;
          return {
            value: item.departmentId,
            label: item.departmentName,
            children: children, // 只有有子项时才会有 children
          };
        })
        .filter((item) => item.children); // 过滤掉没有 children 的项
    },
    handleDeptVisibleChange(visible) {
      if (visible && this.departmentOptions.length === 0) {
        // 只在第一次展开时加载数据
        this.getDepartment();
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        doctorId: null,
        doctorAdminId: null,
        doctorName: null,
        doctorIdCard: null,
        doctorDepartmentId: null,
        doctorPhoneNumber: null,
        doctorLevelId: null,
        doctorMaxWorkHour: null,
        doctorRating: null,
        doctorDescription: null,
        doctorSpecialty: null,
        doctorStatus: null,
        doctorCreateTime: null,
        doctorUpdateTime: null,
        doctorDelete: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.doctorId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getAllAdmins();
      this.open = true;
      this.title = "添加医生";
    },
    // 修改医生状态
    handleStatusChange(row) {
      // 原始值
      const oldStatus = row.doctorStatus;
      // 新值（switch 已经切换过了）
      const newStatus = oldStatus;

      // 需要回滚时的值（即切换前的状态）
      const rollbackStatus = oldStatus === 0 ? 1 : 0;

      this.$confirm(
        `是否确认将${row.doctorName}医生的状态更新为 ${
          newStatus === 0 ? "启用" : "禁用"
        }?`,
        "确认状态修改",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 这里调用后端接口
          updateDoctorStatus(row.doctorId, row.doctorAdminId).then((res) => {
            if (res.code !== 200) {
              // 如果返回的状态码不是200，说明更新失败
              this.$message.error("状态更新失败");
              row.doctorStatus = rollbackStatus; // 回滚状态
              return;
            }
            this.$message.success("状态更新成功");
          });
        })
        .catch(() => {
          row.doctorStatus = rollbackStatus;
          this.$message.info("已取消");
        });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getDepartment();
      this.getAllAdmins();
      this.reset(); // 重置表单数据
      this.form = { ...row }; // 直接从 row 赋值给 form，确保创建一个新的对象
      if (this.form.doctorLevelId != null) {
        this.form.doctorLevelId = String(this.form.doctorLevelId);
      }
      this.open = true; // 显示对话框
      this.title = "修改医生"; // 设置对话框标题
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.doctorId != null) {
            if (!Array.isArray(this.form.doctorDepartmentId)) {
              this.form.doctorDepartmentId = [this.form.doctorDepartmentId];
            }

            console.log("表单", this.form);
            updateDoctor(this.form).then((response) => {
              if (response.code !== 200) {
                this.$modal.msgError("修改失败");
                return;
              }
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDoctor(this.form).then((response) => {
              console.log(response);
              if (response.data.code !== 200) {
                this.$modal.msgError("新增失败");
                return;
              }
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const doctorIds = row.doctorId || this.ids;
      const doctorName = row.doctorName;

      this.$modal
        .confirm('是否确认删除"' + doctorName + '"医生？')
        .then(() => {
          // 用户点击确认
          return deleteDoctor(doctorIds);
        })
        .then((res) => {
          console.log(res);
          if (res.code !== 200) {
            this.$message.error("删除失败");
            return;
          }
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {
          // 用户点击取消
          this.$message.info("已取消");
        });
    },
  },
};
</script>
.